package com.jboost.modules.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jboost.common.api.dto.message.BusMessageDTO;
import com.jboost.common.api.vo.Result;
import com.jboost.common.constant.CommonConstant;
import com.jboost.common.constant.MsgConstant;
import com.jboost.common.constant.WebsocketConst;
import com.jboost.common.domain.RoleCodeConstant;
import com.jboost.common.exception.JBoostException;
import com.jboost.common.system.api.ISysBaseAPI;
import com.jboost.common.system.vo.LoginUser;
import com.jboost.common.util.oConvertUtils;
import com.jboost.modules.system.entity.SysAnnouncementSend;
import com.jboost.modules.system.model.AnnouncementSendModel;
import com.jboost.modules.system.service.ISysAnnouncementSendService;
import com.jboost.modules.system.vo.AnnouncementSendModelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title: Controller
 * @Description: 用户通告阅读标记表
 * @Author: JBoost
 * @Date:  2019-02-21
 * @Version: V1.0
 */
@Api(tags = "消息通知相关")
@RestController
@RequestMapping("/sys/sysAnnouncementSend")
@Slf4j
public class SysAnnouncementSendController {
	@Autowired
	private ISysAnnouncementSendService sysAnnouncementSendService;
	@Autowired
	private ISysBaseAPI iSysBaseAPI;

	/**
	  * 分页列表查询
	 * @param sysAnnouncementSend
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<SysAnnouncementSend>> queryPageList(SysAnnouncementSend sysAnnouncementSend,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<SysAnnouncementSend>> result = new Result<IPage<SysAnnouncementSend>>();
		QueryWrapper<SysAnnouncementSend> queryWrapper = new QueryWrapper<SysAnnouncementSend>(sysAnnouncementSend);
		Page<SysAnnouncementSend> page = new Page<SysAnnouncementSend>(pageNo,pageSize);
		//排序逻辑 处理
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		if(oConvertUtils.isNotEmpty(column) && oConvertUtils.isNotEmpty(order)) {
			if("asc".equals(order)) {
				queryWrapper.orderByAsc(oConvertUtils.camelToUnderline(column));
			}else {
				queryWrapper.orderByDesc(oConvertUtils.camelToUnderline(column));
			}
		}
		IPage<SysAnnouncementSend> pageList = sysAnnouncementSendService.page(page, queryWrapper);
		//log.info("查询当前页："+pageList.getCurrent());
		//log.info("查询当前页数量："+pageList.getSize());
		//log.info("查询结果数量："+pageList.getRecords().size());
		//log.info("数据总数："+pageList.getTotal());
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	/**
	  *   添加
	 * @param sysAnnouncementSend
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<SysAnnouncementSend> add(@RequestBody SysAnnouncementSend sysAnnouncementSend) {
		Result<SysAnnouncementSend> result = new Result<SysAnnouncementSend>();
		try {
			sysAnnouncementSendService.save(sysAnnouncementSend);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	  *  编辑
	 * @param sysAnnouncementSend
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<SysAnnouncementSend> eidt(@RequestBody SysAnnouncementSend sysAnnouncementSend) {
		Result<SysAnnouncementSend> result = new Result<SysAnnouncementSend>();
		SysAnnouncementSend sysAnnouncementSendEntity = sysAnnouncementSendService.getById(sysAnnouncementSend.getId());
		if(sysAnnouncementSendEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = sysAnnouncementSendService.updateById(sysAnnouncementSend);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}

		return result;
	}

	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<SysAnnouncementSend> delete(@RequestParam(name="id",required=true) String id) {
		Result<SysAnnouncementSend> result = new Result<SysAnnouncementSend>();
		SysAnnouncementSend sysAnnouncementSend = sysAnnouncementSendService.getById(id);
		if(sysAnnouncementSend==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = sysAnnouncementSendService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}

		return result;
	}

	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<SysAnnouncementSend> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<SysAnnouncementSend> result = new Result<SysAnnouncementSend>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.sysAnnouncementSendService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<SysAnnouncementSend> queryById(@RequestParam(name="id",required=true) String id) {
		Result<SysAnnouncementSend> result = new Result<SysAnnouncementSend>();
		SysAnnouncementSend sysAnnouncementSend = sysAnnouncementSendService.getById(id);
		if(sysAnnouncementSend==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(sysAnnouncementSend);
			result.setSuccess(true);
		}
		return result;
	}

	/**
	 * @功能：更新用户系统消息阅读状态
	 * @param json
	 * @return
	 */
	@PutMapping(value = "/editByAnntIdAndUserId")
	public Result<SysAnnouncementSend> editById(@RequestBody @ApiParam(value = "传anntId") JSONObject json) {
		Result<SysAnnouncementSend> result = new Result<SysAnnouncementSend>();
		String anntId = json.getString("anntId");
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda();
		updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG);
		updateWrapper.set(SysAnnouncementSend::getReadTime, new Date());
		updateWrapper.last("where annt_id ='"+anntId+"' and user_id ='"+userId+"'");
		SysAnnouncementSend announcementSend = new SysAnnouncementSend();
		sysAnnouncementSendService.update(announcementSend, updateWrapper);
		result.setSuccess(true);
		return result;
	}

	/**
	 * @功能：获取我的消息
	 * @return
	 */
	@ApiOperation(value = "获取我的消息列表-分页")
	@GetMapping(value = "/getMyAnnouncementSend")
	public Result<IPage<AnnouncementSendModel>> getMyAnnouncementSend(AnnouncementSendModel announcementSendModel,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		Result<IPage<AnnouncementSendModel>> result = new Result<IPage<AnnouncementSendModel>>();
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		announcementSendModel.setUserId(userId);
		announcementSendModel.setPageNo((pageNo-1)*pageSize);
		announcementSendModel.setPageSize(pageSize);
		Page<AnnouncementSendModel> pageList = new Page<AnnouncementSendModel>(pageNo,pageSize);
		pageList = sysAnnouncementSendService.getMyAnnouncementSendPage(pageList, announcementSendModel);
		result.setResult(pageList);
		result.setSuccess(true);
		return result;
	}

	 /**
	  * @功能：获取我的已读未读消息列表与个数
	  * @return
	  */
	 @ApiOperation(value = "获取我的已读未读消息列表与个数")
	 @GetMapping(value = "/getMyAnnouncementSendWithTotal")
	 public Result<AnnouncementSendModelVo> getMyAnnouncementSendWithTotal(AnnouncementSendModel announcementSendModel) {
		 Result<AnnouncementSendModelVo> result = new Result<>();
		 LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 String userId = sysUser.getId();
		 announcementSendModel.setUserId(userId);
		 List<AnnouncementSendModel> sendModels = sysAnnouncementSendService.getMyAnnouncementSendList(announcementSendModel);
		 AnnouncementSendModelVo announcementSendModelVo = new AnnouncementSendModelVo();
		 if (CollUtil.isNotEmpty(sendModels)) {
			 List<AnnouncementSendModel> notReadList = sendModels.stream().filter(a -> "0".equals(a.getReadFlag())).collect(Collectors.toList());
			 announcementSendModelVo.setNotReadMsgList(notReadList);
			 announcementSendModelVo.setNotReadTotal(CollUtil.isEmpty(notReadList) ? 0 : notReadList.size());

			 List<AnnouncementSendModel> isReadList = sendModels.stream().filter(a -> "1".equals(a.getReadFlag())).collect(Collectors.toList());
			 announcementSendModelVo.setIsReadMsgList(isReadList);
			 announcementSendModelVo.setIsReadTotal(CollUtil.isEmpty(isReadList) ? 0 : isReadList.size());
		 }
		 result.setResult(announcementSendModelVo);
		 result.setSuccess(true);
		 return result;
	 }

	/**
	 * @功能：一键已读
	 * @return
	 */
	@ApiOperation(value = "全部已读")
	@PutMapping(value = "/readAll")
	public Result<SysAnnouncementSend> readAll() {
		Result<SysAnnouncementSend> result = new Result<SysAnnouncementSend>();
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda();
		updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG);
		updateWrapper.set(SysAnnouncementSend::getReadTime, new Date());
		updateWrapper.last("where user_id ='"+userId+"'");
		SysAnnouncementSend announcementSend = new SysAnnouncementSend();
		sysAnnouncementSendService.update(announcementSend, updateWrapper);
		result.setSuccess(true);
		result.setMessage("全部已读");
		return result;
	}

	@ApiOperation(value = "清空消息")
	@PutMapping(value = "/clearMyMsg")
	public Result<?> clearMyMsg(@ApiParam(name = "readFlag", type = "string", value = "已未读标志位, '0' -> 未读, '1' -> 已读 ") @RequestParam String readFlag) {
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		LambdaUpdateWrapper<SysAnnouncementSend> wrapper = new LambdaUpdateWrapper<>();
		wrapper.eq(SysAnnouncementSend::getUserId, sysUser.getId())
				.eq(SysAnnouncementSend::getReadFlag, readFlag)
				.set(SysAnnouncementSend::getIsVisible, "0");
		sysAnnouncementSendService.update(wrapper);
		return Result.OK();
	}

	@ApiOperation(value = "修改消息为已读")
	@PutMapping(value = "/updateReadFlag")
	public Result<?> updateReadFlag(@ApiParam(name = "msgId", type = "string", value = "消息ID") @RequestParam String msgId) {
		SysAnnouncementSend announcementSend = sysAnnouncementSendService.getById(msgId);
		if (announcementSend == null) {
			throw new JBoostException("消息不存在");
		}
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		if ( !announcementSend.getUserId().equals(sysUser.getId()) ){
			throw new JBoostException("不能处理别人的消息");
		}
		LambdaUpdateWrapper<SysAnnouncementSend> wrapper = new LambdaUpdateWrapper<>();
		wrapper.eq(SysAnnouncementSend::getId, msgId)
				.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG)
				.set(SysAnnouncementSend::getReadTime, new Date());
		sysAnnouncementSendService.update(wrapper);
		JSONObject obj = new JSONObject();
		obj.put(WebsocketConst.UNREAD_NUM, sysAnnouncementSendService.count(new LambdaQueryWrapper<SysAnnouncementSend>().eq(SysAnnouncementSend::getUserId,sysUser.getId()).eq(SysAnnouncementSend::getReadFlag,"0")) );
		return Result.OK(obj);
	}

	@GetMapping(value = "/testMsg")
	public Result<?> testMsg(){
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		BusMessageDTO busMessageDTO = new BusMessageDTO();
		busMessageDTO.setCategory("1");
		busMessageDTO.setContent(StrUtil.format(MsgConstant.HANDLER_MSG, MsgConstant.COURSE_AUDIT, MsgConstant.PROJECT_REPORT_STR));
		busMessageDTO.setFromUser(loginUser.getUsername());
		List<String> userIdsByRoleCode = iSysBaseAPI.getUserIdsByRoleCode(RoleCodeConstant.BUSINESS_MANAGER);
		busMessageDTO.setToUser(String.join(",", userIdsByRoleCode));
		iSysBaseAPI.sendBusAnnouncement(busMessageDTO);
		return Result.OK();
	}

}
